package problems;

import java.util.ArrayList;
import java.util.List;

import lib.MathLib;

public class Euler037 extends AbstractEuler {

	@Override
	public Number calculate() {
		List<Integer> truncatablePrimes = new ArrayList<Integer>();
		
		for (int i = 8; truncatablePrimes.size() < 11; i++) {
			if (isTruncatable(i)) {
				truncatablePrimes.add(i);
			}
		}
		
		return MathLib.getSum(truncatablePrimes);
	}
	
	private boolean isTruncatableOnSide(StringBuffer i, boolean isLeftSide) {
		Integer testValue = Integer.valueOf(i.toString());
		if (!MathLib.isPrime(testValue)) {
			return false;
		} else {
			if (i.length() > 1) {
				StringBuffer truncated = isLeftSide ?
					new StringBuffer(i).deleteCharAt(0) :
					new StringBuffer(i).deleteCharAt(i.length() - 1);
				
				if (isTruncatableOnSide(truncated, isLeftSide)) {
					return true;
				} else {
					return false;
				}
			} else {
				return true;
			}
		}
	}
	
	private boolean isTruncatable(int i) {
		StringBuffer asStrBuf = new StringBuffer().append(i);
		return
			isTruncatableOnSide(asStrBuf, false) &&
			isTruncatableOnSide(asStrBuf, true);
	}

	@Override
	protected Number getCorrectAnswer() {
		return 748317L;
	}

}
